package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.EmployeeComparator;
import cc.eddic.pratice.programmingparadigms.EmployeePredicate;
import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.emp02list.EmployeeList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmployeeListScwImpl implements EmployeeList {

    private static final Logger log = LoggerFactory.getLogger(ResultListScwImpl.class);
    private Employee[] employees;
    private int index;


    public void add(Employee employee) {
        if (index + 1 == employees.length) {
            Employee[] newEmployee = new Employee[employees.length * 2];
            for (int i = 0; i < employees.length; i++) {
                newEmployee[i] = employees[i];
                employees = newEmployee;
            }
        }
        employees[index] = employee;
        index++;
    }


    public Employee get(int index) {
        if (index > size() - 1) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return employees[index];
    }


    public int size() {
        return index;
    }

    @Override
    public Employee find(EmployeePredicate predicate) {
        for (int i = 0; i < size(); ++i) {
            Employee r = get(i);
            if (predicate.test(r)) {
                return r;
            }
        }
        return null;
    }

    @Override
    public void sort(EmployeeComparator comparator) {
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                // 什么情况下要交换
                if (comparator.compare(employees[j], employees[j + 1]) > 0) {
                    // 交换
                    Employee temp = employees[j];
                    employees[j] = employees[j + 1];
                    employees[j + 1] = temp;
                }
            }
        }
    }


}
